import json
import base64
from PIL import Image
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.iai.v20200303 import iai_client, models

def pngTojpg(rootpath):
    im = Image.open(rootpath+'screenshot.png')
    im = im.convert('RGB')
    im.save(rootpath+'screenshot.jpg', quality=95)

def imgbase64(path):
    with open(path, "rb") as image_file:
        encodedImage = str(base64.b64encode(image_file.read()))[2:-5]
    # imgBase64 = "data:image/jpeg;base64," + encodedImage
    imgBase64 =  encodedImage
    return imgBase64

def faceScore(url,imgsrc):
    img64 = imgbase64(imgsrc)
    try:
        # 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
        # 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
        cred = credential.Credential("AKID1rSqzsWv4yc0A5kAKI1VkjX6PTHq9E4e", "NVNzSfcKmzxjFWZNvEH4cuwjGXZLs9By")
        # 实例化一个http选项，可选的，没有特殊需求可以跳过
        httpProfile = HttpProfile()
        httpProfile.endpoint = "iai.tencentcloudapi.com"

        # 实例化一个client选项，可选的，没有特殊需求可以跳过
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        # 实例化要请求产品的client对象,clientProfile是可选的
        client = iai_client.IaiClient(cred, "ap-chengdu", clientProfile)

        # 实例化一个请求对象,每个接口都会对应一个request对象
        req = models.DetectFaceRequest()
        params = {
            "MaxFaceNum": 3,
            "Url": url,
            "Image":img64,
            "NeedFaceAttributes": 1,
            "NeedQualityDetection": 1,
            "FaceModelVersion": "3.0",
            "NeedRotateDetection": 1
        }
        req.from_json_string(json.dumps(params))

        # 返回的resp是一个DetectFaceResponse的实例，与请求对象对应
        resp = client.DetectFace(req)
        # 输出json格式的字符串回包
        resjson = resp.to_json_string()
        return resjson
    except TencentCloudSDKException as err:
        print(err)
        return json.dumps({"msg":"识别失败"})

